import React, { useEffect, useState } from 'react'
import { Button, Form, message } from 'antd'
import { connect, history } from 'umi'
import {
	Basics,
	Referrer,
	CurrentFollower,
	ClueRecommendationRecord,
} from '../components'
import AccordingToRecords from '../components/AccordingToRecords'
import Styles from './index.less'
import {
	clueUpdate,
	getClueDetail,
	getKeyValueByType,
	saveClue,
} from '@/service/merchantCenter/clue'
import { getProvinceDataByCityName } from '@/service/common'

const add = (props: any) => {
	// eslint-disable-next-line react/destructuring-assignment
	const routerQuery = props.location.query
	// eslint-disable-next-line prefer-destructuring
	const pageType = routerQuery.pageType
	const clueId = routerQuery.id
	const [loading, setLoading] = useState(false)
	const [detailRecord, setDetailRecord] = useState<any>({})
	const [basicsForm] = Form.useForm()
	const [referrerForm] = Form.useForm()
	const [currentFollowerForm] = Form.useForm()
	const [accordingToRecordsValue, setAccordingToRecordsValue] = useState([])
	const [name, setName] = useState('')
	const [followPerson, setFollowPerson] = useState<any>()
	const [mainBodyId, setMainBody] = useState('') // 主体ID
	const [orgId, setOrgId] = useState('') // 公司ID
	const [cityId, setCityId] = useState('') // 城市ID
	const [source, setSource] = useState('') // 来源类型
	const [keysList, setKeysList] = useState([]) // 推荐人类型

	useEffect(() => {
		if (cityId) {
			currentFollowerForm.setFieldsValue({
				followUserId: undefined,
				followMobile: '',
				followTime: '',
			})
		}
	}, [mainBodyId, orgId, cityId])

	useEffect(() => {
		if (pageType !== 'add' && clueId) {
			getClueDetail({ id: clueId }).then((res: any) => {
				if (res.data) {
					const obj = { ...res?.data }
					if (obj?.followUserId === 0) {
						obj.followUserId = ''
					}
					if (obj?.followTime === '1970-01-01 00:00:00') {
						obj.followTime = ''
					}
					setSource(obj?.source?.toString())
					setName(obj?.followUserName)
					setMainBody(obj?.subject)
					setFollowPerson(obj?.followUserId)
					setOrgId(obj?.orgId)
					setCityId(obj?.cityId)
					if (res?.data.cityName) {
						getProvinceDataByCityName({
							cityName: res?.data.cityName,
						}).then((result: any) => {
							if (result.data) {
								setDetailRecord({
									...res.data,
									cityId: [
										result?.data?.provinceId,
										res?.data?.cityId,
									],
								})
							}
						})
					}
				}
			})
		}
	}, [])
	useEffect(() => {
		getKeyValueByType({ type: 'Referrer_Type' }).then((res: any) => {
			if (res.data) {
				setKeysList(res.data)
			}
		})
	}, [])
	// eslint-disable-next-line consistent-return
	const onSave = async () => {
		setLoading(true)
		try {
			const basicsFormData = await basicsForm.validateFields()
			let referrerFormData = await referrerForm.validateFields()
			const currentFollowerFormData =
				await currentFollowerForm.validateFields()
			if (referrerFormData?.existPhone) {
				referrerFormData = {
					...referrerFormData,
					newRecommenderType: '',
					newPhone: '',
					newDriverId: '',
					newUserName: '',
					newBankAccount: '',
					newAccountBankName: '',
					newBranchBankName: '',
				}
			} else {
				referrerFormData = {
					...referrerFormData,
					existPhone: '',
					existDriverId: '',
					existUserName: '',
					existBankAccount: '',
					existAccountBankName: '',
					existBranchBankName: '',
				}
			}
			if (
				!referrerFormData ||
				(['4', '5'].includes(basicsFormData?.source) &&
					referrerFormData?.phoneStatus === 'false' &&
					referrerFormData?.newRecommenderType !== 2)
			) {
				message.warning(
					referrerFormData?.newRecommenderType
						? '司机联系电话不存在'
						: '渠道联系电话不存在',
				)
				setLoading(false)
			} else {
				const formD = {
					...basicsFormData,
					...referrerFormData,
					...currentFollowerFormData,
				}
				if (formD?.cityId) {
					formD.cityId = formD?.cityId?.[1] || formD.cityId
				}
				if (pageType === 'edit') {
					formD.traceList = accordingToRecordsValue
					formD.id = clueId
					const res = await clueUpdate(formD)
					if (res.success) {
						message.success('保存成功')
						history.push({
							pathname: '/merchantCenter/clue/list',
						})
					}
					setLoading(false)
					return false
				}
				const res = await saveClue(formD)
				if (res.success) {
					message.success('保存成功')
					history.push({ pathname: '/merchantCenter/clue/list' })
				}
				setTimeout(() => setLoading(false), 1000)
			}
		} catch (error) {
			setTimeout(() => setLoading(false), 1000)
		}
	}
	return (
		<div className={Styles.add}>
			<Basics
				pageType={pageType}
				basicsForm={basicsForm}
				detailRecord={detailRecord}
				user={props?.user}
				mainBodyId={mainBodyId}
				setMainBody={setMainBody}
				orgId={orgId}
				setOrgId={setOrgId}
				setCityId={setCityId}
				setSource={setSource}
				setName={setName}
			/>
			{/* 推荐人 */}
			{source === '4' || source === '5' ? (
				<Referrer
					pageType={pageType}
					referrerForm={referrerForm}
					detailRecord={detailRecord}
					source={source}
					keysList={keysList}
				/>
			) : (
					''
				)}

			{/* 当前跟进人 */}
			<CurrentFollower
				pageType={pageType}
				setName={setName}
				currentFollowerForm={currentFollowerForm}
				detailRecord={detailRecord}
				setFollowPerson={setFollowPerson}
				mainBodyId={mainBodyId}
				orgId={orgId}
				cityId={cityId}
			/>
			{/* 跟进记录 */}
			{detailRecord?.status && (
				<>
					<AccordingToRecords
						name={name}
						clueId={clueId}
						pageType={pageType}
						status={detailRecord?.status}
						followPerson={
							followPerson || detailRecord?.followUserId
						}
						setAccordingToRecordsValue={setAccordingToRecordsValue}
						referrerForm={referrerForm}
					/>
				</>
			)}
			{/* 线索推荐记录 */}
			{source === '4' || source === '5' ? (
				<ClueRecommendationRecord
					detailRecord={detailRecord}
					pageType={pageType}
					clueId={clueId}
				/>
			) : (
					''
				)}

			<div className={Styles.operation}>
				{pageType !== 'detail' && (
					<Button
						type="primary"
						htmlType="submit"
						loading={loading}
						onClick={onSave}>
						保存
					</Button>
				)}

				<Button
					style={{ marginLeft: '5px;' }}
					onClick={() => {
						history.go(-1)
					}}>
					取消
				</Button>
			</div>
		</div>
	)
}
export default connect(({ user }: any) => ({ user }))(add)
